import random
import re
from google.appengine.ext import webapp

class CoinToss(webapp.RequestHandler):
    def get(self):
        output = '<pre>'
        count = {}
        for tc in xrange(64):
            seq = ''.join([random.choice('TH') for i in xrange(64)])
            match = re.findall(r'(H{2,}|T{2,})', seq)
            if match:
                match.sort(key=lambda x: len(x), reverse=True)
                m0 = match[0]
                count[len(m0)] = count.get(len(m0), 0) + 1
                seq = seq.replace(m0, '<span style="color:#cc6600;font-weight:bold">'+m0+'</span>')
                for m in match[1:]:
                    if len(m) == len(m0):
                        seq = seq.replace(m, '<span style="color:#cc0066;font-weight:bold">'+m+'</span>')
                seq += ' %2d'%len(match[0])
            if tc%2 == 1:
                output += seq + '<br>'
            else:
                output += seq + ' '
        for x, n in count.items():
            output += "%2d: %2d<br>"%(x, n)
        output += '</pre>'
        self.response.out.write(output)
